const Category = require("../model/category.model");
const User = require("../model/user.model");
const Type = require("../model/type.model");
const Record = require("../model/record.model");

// 使用模糊查询需要先引入Op
const seq = require("sequelize");
const moment = require("moment/moment");
const {createRecord} = require("./record.service");
const Op = seq.Op;

class CategoryService {
    /**
     * 创建
     * @returns {Promise<{code: string, message: string}>}
     * @param category
     */
    async createCategory(category) {
        const { id } = await createRecord();
        try {
            const res = await Category.create({...category,record_id: id});
            return res.dataValues;
        }catch (err) {
            console.log(err)
            return null
        }

    }

    /**
     * 更新
     * @param id
     * @param category
     * @returns {Promise<boolean>}
     */
    async updateCategory(id, category) {
        const updateOption = {}
        category.amount_raised && Object.assign(updateOption, {amount_raised: seq.literal('amount_raised + '+category.amount_raised)})
        category.status && Object.assign(updateOption, {status: category.status})
        const res = await Category.update(updateOption, {where: {id}});
        return res[0] > 0;
    }

    /**
     * 删除
     * @param id
     * @returns {Promise<boolean>}
     */

    async removeCategory(id) {
        const res = await Category.destroy({where: {id}});
        return res > 0;
    }

    /**
     * 恢复
     * @param id
     * @returns {Promise<boolean>}
     */

    async restoreCategory(id) {
        const res = await Category.restore({where: {id}});
        return res > 0;
    }

    is_vip
    async findCategory({pageNum, pageSize, title, nick_name, type_id,is_user,user_id,is_vip}) {
        const offset = (pageNum - 1) * pageSize;
        const whereOpt1 = {};
        const whereOpt2 = {};
        const whereOpt3 = {};
        let orderBy = ["createdAt", "DESC"];


        nick_name &&
        Object.assign(whereOpt1, {
            nick_name: {
                [Op.like]: `%${nick_name}%`,
            },
        });

        title &&
        Object.assign(whereOpt2, {
            title: {
                [Op.like]: `%${title}%`,
            },
        });

        is_user && Object.assign(whereOpt2, {status:1});

        user_id && Object.assign(whereOpt2, {user_id});

        type_id && Object.assign(whereOpt3, {id: type_id});

        if(is_vip) orderBy = ["user_info","is_vip", "DESC"]

        const {count, rows} = await Category.findAndCountAll({
            offset: offset,
            limit: pageSize * 1,
            where: whereOpt2,
            include: [
                {
                    model: User,
                    as: "user_info",
                    where: whereOpt1,
                },
                {
                    model: Type,
                    as: "type_info",
                    where: whereOpt3,
                },
                {
                    model: Record,
                    as: "record_info",
                },
            ],
            order:[orderBy],
        });

        return {
            pageNum,
            pageSize,
            total: count,
            list: rows,
        };
    }

    async findCategoryInfo(id) {
        const whereOpt = {};
        id && Object.assign(whereOpt, {id});

        const res = await Category.findOne({
            where: whereOpt,
            include: [{
                model: Record,
                as: "record_info",
            }, {
                model: User,
                as: "user_info",
            },
            {
                model: Type,
                as: "type_info",
            }]
        });

        return res ? res.dataValues : null;
    }

    // 改变所有项目的状态
    async changeCategoryStatus() {
        await Category.update({status:3}, {where: {
            end_time:{
                [Op.lt]: moment(new Date()).format('YYYY/MM/DD HH:mm:ss')
            }
        }});
    }
}

module.exports = new CategoryService();
